<?php
require_once path('app') . 'libraries/simple_html_dom.php';

class Load_Task
{
    private $providerBaseUrl = 'http://minhngoc.com.vn/so-dau-duoi/mien-nam.html?page=';
    private $providerMaxPage = 62;
    private $cacheTimeout = 600; # minutes

    public function run($param = 'all')
    {
        if ($param == 'all')
        {
            for ($i = $this->providerMaxPage; $i > 0; $i--) {
                $this->parse($this->download_html($this->providerBaseUrl . $i));

                echo "OK\n";
                flush();
            }
        }
        else if ($param = 'f')
        {
            $this->parse($this->download_html($this->providerBaseUrl, false));
        }
    }

    protected function download_html($url, $useCache = true)
    {
        echo "\nDownloading URL $url ... ";
        ob_flush();
        if ($useCache)
        {
            return Cache::remember(md5($url), function () use ($url) {
                return file_get_contents($url);
            }, $this->cacheTimeout);
        }
        else
        {
            return file_get_contents($url);
        }

    }

    /**
     * Thực hiện phân tích một document html để nhận về thứ, ngày, các đài và các số
     * @param $html
     */
    protected function parse($html)
    {
        $dom = str_get_html($html);
        $resultNodes = $dom->find('#sodauduoi .sodauduoi_miennam');
        foreach ($resultNodes as $curResultNode) {
            $ngayNode = $curResultNode->find('.ngay', 0);

            # extract ngay

            $date = convertDate($ngayNode->plaintext);

            $kqNodes = $curResultNode->find('.kq');
            foreach ($kqNodes as $curKqNode) {
                $channelNamePattern = '%^([^<]+)%';
                preg_match($channelNamePattern, $curKqNode->innertext, $matches);
                $channel = $matches[1];

                $firstNumber = $curKqNode->find('.xanh', 0)->plaintext;
                $lastNumber = $curKqNode->find('.do', 0)->plaintext;

                Result::updateOrInsert(array(
                    'date' => $date,
                    'first' => $firstNumber,
                    'last' => $lastNumber,
                    'channel_id' => Channel::idByName($channel),
                    'weekday' => date('w', strtotime($date)),
                ));
            }

        }
    }


}